<template>
  <div>
    <el-card class="box-card">
      <el-form ref="form" :model="queryConditions" label-width="80px">
        <!-- 使用el-row和el-col实现水平布局 -->
        <el-row :gutter="20">
          <el-col :span="5.5">
            <el-form-item label="用户名">
              <el-input
                  size="small"
                  v-model="queryConditions.username"
                  placeholder="请输入用户名"
                  prefix-icon="el-icon-user">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5.5">
            <el-form-item label="手机号">
              <el-input
                  size="small"
                  v-model="queryConditions.phone"
                  placeholder="请输入手机号"
                  prefix-icon="el-icon-phone">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="日期区间">
              <el-date-picker
                  size="small"
                  v-model="dateRange"
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item>
              <el-button type="primary" size="small" @click="handleQuery">查询</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item>
              <el-button type="primary" size="small" @click="resetConditions">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card >
      <!--批量删除按钮 批量删除选中数据-->
      <el-button type="danger" size="small" @click="handleDeleteSelected">批量删除</el-button>
      <!--添加用户按钮-->
      <el-button type="primary" size="small" @click="handleAdd">添加用户</el-button>
      <el-table
          ref="multipleTable"
          :data="userList"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            >
        </el-table-column>
        <el-table-column
            prop="id"
            label="编号"
            width="75px">
        </el-table-column>
        <el-table-column
            prop="username"
            label="用户名"
            width="100px">
        </el-table-column>
        <el-table-column
            prop="password"
            label="密码">
        </el-table-column>
        <el-table-column
            prop="phone"
            label="手机号">
        </el-table-column>
        <el-table-column
            prop="roleName"
            label="角色">
        </el-table-column>
        <el-table-column
            prop="createTime"
            label="入职时间">

        </el-table-column>
        <el-table-column
            prop="money"
            label="余额" width="100px">
        </el-table-column>
        <el-table-column
            prop="sex"
            label="性别" width="75px">
          <template slot-scope="scope">
            <el-tag
                :type="scope.row.sex == '1' ? 'success' : 'danger'"
                disable-transitions>{{scope.row.sex == '1' ? '男':'女'}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          background
          class="pagination-margin"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="this.queryConditions.pageNum"
          :page-sizes="[8, 6, 3, 1]"
          :page-size="this.queryConditions.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="this.total">
      </el-pagination>
    </el-card>

    <!--添加用户弹窗-->
    <el-dialog
        :title=title
        :visible.sync="dialogFormVisible"
        width="30%"
        :close-on-click-modal="false">
      <el-form :model="userForm" :rules="rules" ref="userForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="userForm.password"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="余额" prop="money">
          <el-input v-model="userForm.money"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="userForm.sex">
            <el-radio label="1">男</el-radio>
            <el-radio label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "user",
  data() {
    var validatePhone = (rule, value, callback) => {
      if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号'));
      } else {
        callback();
      }
    }
    var validatePass = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码长度不能小于6位'));
      } else {
        callback();
      }
    }
    return {
      queryConditions: {
        username: '',
        phone: '',
        startTime: '',
        endTime: '',
        pageNum:1,
        pageSize:8
      },
      dateRange: '',
      userList:[],
      total:null,
      ids:[],
      dialogFormVisible: false,
      title: '',
      userForm: {
        username: '',
        password: '',
        phone: '',
        money: 0,
        sex: '1'
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 11, message: '长度在 3 到 11 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true,  trigger: 'blur', validator: validatePass}
        ],
        phone: [
          { trigger: 'blur', validator: validatePhone }
        ],
        money: [
          { required: false, message: '请输入余额', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    //将日期区间转换为时间格式,再进行查询
    handleQuery() {
      console.log(this.dateRange)
      this.queryConditions.pageNum=1

      this.findAll();
    },
    //查询全部
    findAll(){
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryConditions.startTime = this.dateRange[0];
        this.queryConditions.endTime = this.dateRange[1];
      }
      axios.get("user/list",{
        params: this.queryConditions
      }).then(res => {
        if (res.code == '40003') {
          this.$confirm('用户状态过时,请重新登录. 点击取消,留在当前页.点击确定跳转登录页', '系统提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => { // 点击确定
            this.$router.push("/")
          }).catch(() => { // 点击取消

          });
        } else {
          console.log(res.data)
          this.userList = res.data.list
          this.total = res.data.total
        }
      }).catch(err => {
        console.log(err)
      })
    },
    //每页条数改变,且重新查询
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.queryConditions.pageSize = val;
      this.findAll();
    },
    //设置当前页,且重新查询
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.queryConditions.pageNum = val;
      this.findAll();
    },
    //重置查询条件,且重新查询全部
    resetConditions(){
      this.queryConditions.username='';
      this.queryConditions.phone='';
      this.queryConditions.startTime='';
      this.queryConditions.endTime='';
      this.dateRange='';
      this.handleQuery()
    },
    //点击删除按钮的操作
    handleDelete(row) {
      console.log(row);
      this.$confirm('此操作将永久删除编号为' + row.id + '的用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //删除成功后,重新查询全部
        axios.get("user/delete?id=" + row.id).then(res => {
          if (res.code == '40003') {
            this.$confirm('用户状态过时,请重新登录. 点击取消,留在当前页.点击确定跳转登录页', '系统提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => { // 点击确定
              this.$router.push("/")
            }).catch(() => { // 点击取消

            });
          } else {
            console.log(res);
            if (res.code === 200) {
              this.$message.success(res.msg);
              this.handleQuery();
            } else {
              this.$message.error(res.msg);
            }
          }
        }).catch(error => {
          console.log(error);
        })
      }).catch(() => {
        this.$message.info( '已取消删除');
      });
    },
    //批量删除选中数据
    handleDeleteSelected(){
      //判断是否选中了数据
      if (this.ids.length === 0) {
        this.$message.info('请选择要删除的数据');
        return;
      }
      this.$confirm('此操作将永久删除编号为' + this.ids + '的用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //发送请求删除选中的行
        axios.get("user/deleteBatch?ids=" + this.ids).then(res => {
          if (res.code == '40003') {
            this.$confirm('用户状态过时,请重新登录. 点击取消,留在当前页.点击确定跳转登录页', '系统提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => { // 点击确定
              this.$router.push("/")
            }).catch(() => { // 点击取消

            });
          } else {
            console.log(res);
            if (res.code === 200) {
              this.$message.success(res.msg);
              this.handleQuery();
            } else {
              this.$message.error(res.msg);
            }
          }
        }).catch(error => {
          console.log(error);
        })
      }).catch(() => {
        this.$message.info( '已取消删除');
      });
    },
    //选择数据改变时触发
    handleSelectionChange(val){
      this.ids = []
      //将选中的行的id添加到ids数组中
      val.forEach(item=>{
        this.ids.push(item.id)
      })
    },
    //添加用户按钮
    handleAdd(){
      this.title = '添加用户'
      this.userForm = {
        username: '',
        password: '',
        phone: '',
        money: 0,
        sex: '1'
      }
      //打开添加用户弹窗
      this.dialogFormVisible = true;
    },
    //点击添加表单中的确认按钮进行如下处理
    submitForm() {
      if (this.title === '添加用户'){
        //添加用户
        //校验表单数据
        this.$refs.userForm.validate((valid) => {
          if (valid) {
            axios.post('user/add', this.userForm).then(res => {
              if (res.code == '40003') {
                this.$confirm('用户状态过时,请重新登录. 点击取消,留在当前页.点击确定跳转登录页', '系统提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => { // 点击确定
                  this.$router.push("/")
                }).catch(() => { // 点击取消

                });
              } else {
                if (res.code === 200) {
                  this.$message.success(res.msg);
                  this.dialogFormVisible = false;
                  this.handleQuery();
                  this.$refs.userForm.resetFields();
                } else {
                  this.$message.error(res.msg);
                }
              }
            });
          }
        });
      }else if (this.title === '编辑用户'){
        //编辑用户
        //校验表单数据
        this.$refs.userForm.validate((valid) => {
          if (valid) {
            axios.post('user/update', this.userForm).then(res => {
              if (res.code == '40003') {
                this.$confirm('用户状态过时,请重新登录. 点击取消,留在当前页.点击确定跳转登录页', '系统提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => { // 点击确定
                  this.$router.push("/")
                }).catch(() => { // 点击取消

                });
              } else {
                if (res.code === 200) {
                  this.$message.success(res.msg);
                  this.dialogFormVisible = false;
                  this.handleQuery();
                  this.$refs.userForm.resetFields();
                } else {
                  this.$message.error(res.msg);
                }
              }
            });
          }
        });
      }

    },
    //点击编辑按钮的操作
    handleEdit(row) {
      console.log(row);
      this.title = '编辑用户'
      //打开编辑用户弹窗
      this.dialogFormVisible = true;
      //将当前行的数据赋值给表单
      this.userForm = row;
      // 修复2：确保性别字段为字符串类型
      this.userForm.sex = row.sex.toString();
      console.log(this.userForm)
    }

  },
  created() {
    this.findAll();
  }
}
</script>

<style scoped>

.box-card {
  width: 100%;
  height: 70px;
  margin-bottom: 15px; /* 添加这行来增加卡片间距 */
}

.pagination-margin {
  margin-top: 10px; /* 调整这个值来控制分页向下移动的距离 */
}
</style>